import { UPLOADS_DIR } from "$lib/utils/paths";
import fs from "fs";
import path from "path";

function isSafeFilename(name) {
  if (!name) return false;
  if (name.includes("\0")) return false;
  if (name.includes("..") || name.includes("/") || name.includes("\\")) return false;
  return true;
}

export async function POST({ request }) {
  try {
    const data = await request.json();
    let { filenames } = data;
    if (!filenames) { return new Response(JSON.stringify({ error: "filenames is required" }), { status: 400, headers: { "Content-Type": "application/json" } }); }
    if (typeof filenames === "string") filenames = [filenames];
    const results = filenames.map((filename) => {
      if (!isSafeFilename(filename)) { return { filename, status: "invalid_filename" }; }
      const filePath = path.join(UPLOADS_DIR, filename);
      const resolved = path.resolve(filePath);
      const uploadsResolved = path.resolve(UPLOADS_DIR);
      if (!resolved.startsWith(uploadsResolved + path.sep) && resolved !== uploadsResolved) { return { filename, status: "forbidden" }; }
      if (fs.existsSync(resolved) && fs.statSync(resolved).isFile()) {
        try {
          fs.unlinkSync(resolved);
          return { filename, status: "deleted" };
        } catch (err) {
          return { filename, status: "error", message: err.message };
        }
      } else {
        return { filename, status: "not_found" };
      }
    });

    return new Response(JSON.stringify({ results }), { headers: { "Content-Type": "application/json" } });
  } catch (err) {
    return new Response(JSON.stringify({ error: err.message }), { status: 500, headers: { "Content-Type": "application/json" } });
  }
}
